/**
 * Inventory Management Program
 */

const inventory = [];

// const product = {
//   name: 'bike',
//   quantity: '20'
// }

const getNames = () => {
  const names = [];
  for (const product of inventory) {
    names.push(product.name);
  }
  return names
}

function findProductIndex(name) {
  name = name.toLowerCase();
  // const names = [];
  // for (const product of inventory) {
  //   names.push(product.name);
  // }
  const names = getNames();
  if (names.includes(name)) return names.indexOf(name);
  return -1;
}

function addProduct(product) {
  product.name = product.name.toLowerCase();
  const names = getNames();
  if (names.includes(product.name)) {
    const index = findProductIndex(product.name);
    inventory[index].quantity += product.quantity;
    console.log(product.name + ' quantity updated');
  }
  else {
    inventory.push(product);
    console.log(product.name + ' added to inventory');
  }
}

function removeProduct(name, quantity) {
  name = name.toLowerCase();
  const index = findProductIndex(name);
  if (index >= 0) {
    const newQuantity = inventory[index].quantity - quantity;
    if (newQuantity === 0) inventory.splice(index, 1);
    else if (newQuantity < 0) {
      console.log(`Not enough ${name} available, remaining pieces: ${inventory[index].quantity}`);
    } else {
      inventory[index].quantity = newQuantity;
      console.log(`Remaining ${name} pieces: ${inventory[index].quantity}`);
    }
  } else {
    console.log(`${name} not found`);
  }
}

// run the test
console.log(findProductIndex("Flour"));
addProduct({name: "FLOUR", quantity: 5});
console.log(inventory);
addProduct({name: "FLOUR", quantity: 5});
console.log(inventory);
removeProduct("FLOUR", 5);
console.log(inventory);